int f(int n){ static int r = 0; if (n <= 0) return1; if (n > ...
f(5) = f(3)+2
The line "r = n" changes value of r to 5. Since r
is static, its value is shared be all subsequence
calls. Also, all subsequent calls don't change r
because the statement "r = n" is in a if condition
with n > 3.
f(3) = f(2)+5
f(2) = f(1)+5
f(1) = f(0)+5
f(0) = 1
So f(5) = 1+5+5+5+2 = 18
View all questions of this test
int f(int n){ static int r = 0; if (n <= 0) return1; if (n > ...
Explanation:
The given code is recursively calculating the value of f(n), where n is an integer input. Let's understand the code step by step:
- The function f(n) is defined with a static variable r initialized to 0.
- If n is equal to 0, the function returns 1.
- If n is greater than or equal to 3, r is set to the value of n, and the function calls itself with n-2 as the input argument, and returns the result multiplied by 2.
- If n is less than 3, the function calls itself with n-1 as the input argument, and returns the value of r.
Now, let's calculate the value of f(5) by applying the above steps:
- The input argument is 5, which is greater than or equal to 3. So, r is set to 5, and the function calls itself with 3 as the input argument.
- The input argument is 3, which is equal to 3. So, r is not changed, and the function calls itself with 1 as the input argument.
- The input argument is 1, which is less than 3. So, the function calls itself with 0 as the input argument.
- The input argument is 0, which is equal to 0. So, the function returns 1.
- Now, the previous function call with input argument 1 returns the value of r, which is 5.
- So, the function call with input argument 3 returns 5.
- Now, the initial function call with input argument 5 returns the result of the previous function call multiplied by 2, which is 10.
Therefore, the value of f(5) is 10, which is option D.